<?php

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

class User extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_at';
    protected $defaultSoftDelete = 0;

    /**
     * 关联的数据表。
     *
     * @var string
     */
    protected $table = 'user';
    /**
     * 自动时间戳数据类型
     *
     * @var string
     */
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'create_at';
    protected $updateTime = 'update_at';
    /**
     * 属性默认值。
     *
     * @var array<string>
     */
    protected $attribute = [
        'nickname' => '',
        'mobile' => '',
        'avatar' => '',
        'email' => '',
    ];
    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $field = [
        'mobile',
        'avatar',
        'email',
        'stature',
        'nickname',
        'birthday',
        'career',
        'gender',
        'aim',
        'hobby',
        'status',
        'password',
        'delete_at'
    ];
    /**
     * The attributes that should be cast.
     *
     * @var array<string>
     */
    protected $type = [
        'create_at' => 'timestamp:Y-m-d H:i:s',
        'update_at' => 'timestamp:Y-m-d H:i:s',
        'delete_at' => 'timestamp:Y-m-d H:i:s',
        'hobby' => 'array'
    ];
    // 只读字段
    protected $readonly = ['mobile'];
    // 查询范围
    public function scopeUser($query)
    {
        $query->where('id', request()->uid);
    }
    public function searchNicknameAttr($query, $value, $data)
    {
        !empty($value) && $query->where('nickname|mobile', $value);
    }
    public function searchStatusAttr($query, $value, $data)
    {
        $value > 0 && $query->where('status', $value);
    }
    /**
     * 与 user 的 password 交互。
     */
    protected function setPasswordAttr($val)
    {
        return password_hash($val, PASSWORD_BCRYPT);
    } 
}